import { ipcRenderer, contextBridge } from 'electron'

// --------- 向渲染进程公开某些API ---------
contextBridge.exposeInMainWorld('ipcRenderer', {
  // 监听来自主进程的异步或同步消息
  on(...args: Parameters<typeof ipcRenderer.on>) {
    const [channel, listener] = args
    return ipcRenderer.on(channel, (event, ...args) => listener(event, ...args))
  },
  // 移除通过ipcRenderer.on添加的事件监听器
  off(...args: Parameters<typeof ipcRenderer.off>) {
    const [channel, ...omit] = args
    return ipcRenderer.off(channel, ...omit)
  },
  // 向主进程发送异步消息
  send(...args: Parameters<typeof ipcRenderer.send>) {
    const [channel, ...omit] = args
    return ipcRenderer.send(channel, ...omit)
  },
  // 向主进程发送同步消息
  invoke(...args: Parameters<typeof ipcRenderer.invoke>) {
    const [channel, ...omit] = args
    return ipcRenderer.invoke(channel, ...omit)
  },

  // You can expose other APTs you need here.
  // ...
})

// --------- Preload scripts loading ---------
/**
 * 通过监听 readystatechange事件来判断渲染进程何时准备就绪<br>
 * interactive: 文档已完全加载，但子资源尚未加载完成<br>
 * complete: 文档和子资源加载完成
 * @param condition DocumentReadyState[] 渲染进程的准备状态数组，默认为['complete', 'interactive']。
 */
function domReady(condition: DocumentReadyState[] = ['complete', 'interactive']) {
  return new Promise(resolve => {
    if (condition.includes(document.readyState)) {
      resolve(true)
    } else {
      document.addEventListener('readystatechange', () => {
        if (condition.includes(document.readyState)) {
          resolve(true)
        }
      })
    }
  })
}

/**
 * DOM操作封装
 * <li><b>append：</b>向父元素中安全地添加子元素，确保不会重复添加。</li>
 * <li><b>remove：</b>从父元素中安全地移除子元素，确保仅移除存在的子元素。</li>
  */
const safeDOM = {
  append(parent: HTMLElement, child: HTMLElement) {
    if (!Array.from(parent.children).find(e => e === child)) {
      return parent.appendChild(child)
    }
  },
  remove(parent: HTMLElement, child: HTMLElement) {
    if (Array.from(parent.children).find(e => e === child)) {
      return parent.removeChild(child)
    }
  },
}

/**
 * 加载动画的实现，参考：<br>
 * https://tobiasahlin.com/spinkit<br>
 * https://connoratherton.com/loaders<br>
 * https://projects.lukehaas.me/css-loaders<br>
 * https://matejkustec.github.io/SpinThatShit
 */
function useLoading() {
  const className = `loaders-css__square-spin`
  const styleContent = `
@keyframes square-spin {
  25% { transform: perspective(100px) rotateX(180deg) rotateY(0); }
  50% { transform: perspective(100px) rotateX(180deg) rotateY(180deg); }
  75% { transform: perspective(100px) rotateX(0) rotateY(180deg); }
  100% { transform: perspective(100px) rotateX(0) rotateY(0); }
}
.${className} > div {
  animation-fill-mode: both;
  width: 50px;
  height: 50px;
  background: #fff;
  animation: square-spin 3s 0s cubic-bezier(0.09, 0.57, 0.49, 0.9) infinite;
}
.app-loading-wrap {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #282c34;
  z-index: 9;
}
    `
  const oStyle = document.createElement('style')
  const oDiv = document.createElement('div')

  oStyle.id = 'app-loading-style'
  oStyle.innerHTML = styleContent
  oDiv.className = 'app-loading-wrap'
  oDiv.innerHTML = `<div class="${className}"><div></div></div>`

  return {
    appendLoading() {
      safeDOM.append(document.head, oStyle)
      safeDOM.append(document.body, oDiv)
    },
    removeLoading() {
      safeDOM.remove(document.head, oStyle)
      safeDOM.remove(document.body, oDiv)
    },
  }
}

// ----------------------------------------------------------------------
/**
 * 使用domReady函数在文档加载后执行appendLoading函数加载过度动画
 */
const { appendLoading, removeLoading } = useLoading()
domReady().then(appendLoading)

/**
 * 设置一个监听器，监听渲染进程发来的消息，用以移除加载动画<br>
 * 注意：直接赋值window.onmessage会覆盖之前的监听器，因此这里使用赋值而非addEventListener
 * @param ev 事件对象，包含渲染进程发来的消息
 */
window.onmessage = (ev) => {
  ev.data.payload === 'removeLoading' && removeLoading()
}

setTimeout(removeLoading, 4999)